const express = require('express')
const xlsx = require('xlsx')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath, createExcelFileIfNotExists } = require('../utils/constants.js') // 引入常量
const authenticateToken = require('../utils/authMiddleware.js') // 身份验证中间件

const router = express.Router()
// 使用绝对路径
const filePath = getFilePath('articles')

// 如果文件不存在，创建一个新的 Excel 文件
createExcelFileIfNotExists(filePath, 'articles')

// 发布文章路由 (需要身份验证)
router.post('/publishArticle', authenticateToken, (req, res) => {
  const { title, summary, content } = req.body

  const { userId: authorId, account } = req.user // 从认证用户中获取作者 ID 和账户信息

  // 检查是否提供了必填项
  if (!title || !summary || !content) {
    return sendResponse(res, 400, {}, '请提供标题、概要和正文。')
  }

  const articleId = uuidv4() // 生成文章 ID
  const wordCount = content.length // 计算字数
  const createdAt = new Date().toISOString() // 创建时间

  // 创建新文章数据
  const newArticle = {
    ID: articleId,
    Title: title,
    Summary: summary,
    Content: content,
    CreatedAt: createdAt,
    AuthorID: authorId, // 作者ID为当前认证用户的ID
    AuthorAccount: account, // 作者账户信息
    WordCount: wordCount, // 字数
    ReadCount: 0, // 阅读量初始化为 0
    LikeCount: 0 // 点赞数初始化为 0
  }

  const workbook = xlsx.readFile(filePath)
  const worksheet = workbook.Sheets['articles']
  const articlesData = xlsx.utils.sheet_to_json(worksheet)

  // 将新文章添加到文章数据中
  articlesData.push(newArticle)

  // 将更新后的文章数据写入 Excel 文件
  const newSheet = xlsx.utils.json_to_sheet(articlesData)
  workbook.Sheets['articles'] = newSheet
  xlsx.writeFile(workbook, filePath)

  // 返回发布成功的响应
  return sendResponse(res, 200, { articleId, title, authorId, authorAccount: account }, '文章发布成功！')
})

module.exports = router
